package review;

import java.util.Arrays;

/**
 * 注:在使用二分法查找前保证数组已经排好了序
 * 时间复杂度师logn
 */
public class 二分查找算法 {

    public static int binarySearch(int[] array,int value) {
        int low = 0;
        int high = array.length - 1;
        while (low <= high) {
            int mid = (low + high)/2;
            if(array[mid] == value) {
                return mid;
            }
            if(value < array[mid]) {
                high = mid - 1;
            }
            if(value > array[mid]) {
                low = mid + 1;
            }
        }
        return -1;
    }



    public static void main(String[] args) {
        int[] array = {10,5,2,1,90,80,65,15,6,8};
        // Arrays.binarySearch(new int[]{22,6,5,8,9,2}, 5);
        // 在使用二分法查找之前, 请对数组进行排序
        Arrays.sort(array);
        System.out.println("排序之后的数组为:" + Arrays.toString(array));
        int index = binarySearch(array,80);
        System.out.println("二分法查找的索引位置:" + index);
    }
}
